// CategoryService.java
package com.estore.service;

import com.estore.model.Product;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 商品分类服务类
 */
public class CategoryService {
    private final Map<String, Category> categories = new ConcurrentHashMap<>();
    private final ProductService productService;

    public CategoryService(ProductService productService) {
        this.productService = productService;
        initializeDefaultCategories();
    }

    /**
     * 初始化默认分类
     */
    private void initializeDefaultCategories() {
        // 创建根分类
        Category books = new Category("cat001", "图书");
        Category electronics = new Category("cat002", "电子产品");
        Category health = new Category("cat003", "健康用品");

        categories.put(books.getCategoryId(), books);
        categories.put(electronics.getCategoryId(), electronics);
        categories.put(health.getCategoryId(), health);

        // 创建子分类
        Category programmingBooks = new Category("cat001_1", "编程书籍");
        Category databaseBooks = new Category("cat001_2", "数据库书籍");
        books.addSubCategory(programmingBooks);
        books.addSubCategory(databaseBooks);
        categories.put(programmingBooks.getCategoryId(), programmingBooks);
        categories.put(databaseBooks.getCategoryId(), databaseBooks);

        // 关联现有商品到分类
        programmingBooks.addProduct("p001"); // Java从入门到精通
        programmingBooks.addProduct("p005"); // java从入门到精通
        programmingBooks.addProduct("p006"); // python从入门到精通
        programmingBooks.addProduct("p007"); // C++从入门到精通

        databaseBooks.addProduct("p002"); // 高性能MySQL

        health.addProduct("p003"); // 颈椎康复指南
        health.addProduct("p004"); // 生发秘籍
    }

    /**
     * 删除分类
     * @param categoryId 分类ID
     */
    public void deleteCategory(String categoryId) {
        Category category = categories.get(categoryId);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在: %s".formatted(categoryId));
        }

        // 移除所有子分类的关联
        for (Category subCategory : category.getSubCategories()) {
            subCategory.setParentCategory(null);
        }

        // 如果有父分类，从父分类中移除
        if (category.getParentCategory() != null) {
            category.getParentCategory().removeSubCategory(category);
        }

        categories.remove(categoryId);
    }

    /**
     * 根据分类ID获取分类
     * @param categoryId 分类ID
     * @return 分类对象
     */
    public Category getCategoryById(String categoryId) {
        return categories.get(categoryId);
    }

    /**
     * 获取所有分类
     * @return 分类列表
     */
    public List<Category> getAllCategories() {
        return new ArrayList<>(categories.values());
    }

    /**
     * 给商品分配分类
     * @param productId 商品ID
     * @param categoryId 分类ID
     */
    public void assignProductToCategory(String productId, String categoryId) {
        Product product = productService.findProductById(productId);
        if (product == null) {
            throw new IllegalArgumentException("商品不存在: %s".formatted(productId));
        }

        Category category = categories.get(categoryId);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在: %s".formatted(categoryId));
        }

        category.addProduct(productId);
    }

    /**
     * 从分类中移除商品
     *
     * @param productId  商品ID
     * @param categoryId 分类ID
     * @return 是否成功移除
     */
    public boolean removeProductFromCategory(String productId, String categoryId) {
        Category category = categories.get(categoryId);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在: %s".formatted(categoryId));
        }

        return category.removeProduct(productId);
    }

    /**
     * 根据分类获取商品列表
     * @param categoryId 分类ID
     * @return 商品列表
     */
    public List<Product> getProductsByCategory(String categoryId) {
        Category category = categories.get(categoryId);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在: %s".formatted(categoryId));
        }

        List<Product> products = new ArrayList<>();
        for (String productId : category.getProductIds()) {
            Product product = productService.findProductById(productId);
            if (product != null) {
                products.add(product);
            }
        }
        return products;
    }

    public boolean addCategory(Category category) {
        if (category == null || category.getCategoryId() == null || categories.containsKey(category.getCategoryId())) {
            return false;
        }
        categories.put(category.getCategoryId(), category);
        return true;
    }

    public boolean updateCategory(String categoryId, String categoryName, String description) {
        Category category = categories.get(categoryId);
        if (category == null) {
            return false;
        }
        category.setCategoryName(categoryName);
        category.setDescription(description);
        return true;
    }

    public Category findCategoryById(String categoryId) {
        return getCategoryById(categoryId);
    }

    public boolean removeCategory(String categoryId) {
        if (!categories.containsKey(categoryId)) {
            return false;
        }
        deleteCategory(categoryId);
        return true;
    }

    public boolean addProductToCategory(String categoryId, String productId) {
        try {
            assignProductToCategory(productId, categoryId);
            return true;
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
}
